<template>
  <!-- 线索漏斗分析 -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      height="auto"
      v-loading="loading"
      :dataSource="dataSource"
      :isPagination="false"
      :isSelectColumn="false"
      :isColumnFilter="false"
      selectionType="single"
      :onColumnsChange="columns => this.columns = columns"
    >
      <template slot="controls" slot-scope="props">
        <el-radio-group v-model="radio1" @change="changeClue">
          <el-radio-button
            v-for="(item, index) in radioList"
            :key="index"
            :label="item.value"
          >{{item.text}}</el-radio-button>
        </el-radio-group>
      </template>
    </FilterTable>
  </div>
</template>

<script>
import {
  queryClueSourceReport,
  qryClueFunnelTables,
  getBrandList,
  getSeriesList,
  getSeries,
  getMerge,
  getOrgByOrgType,
  getSaleInfoMaintain
 } from '@/api/report/retail/clueFunnelAnalysis';
import { getlistAllData } from '@/api/common/org/dealerCompany';
import { dictionary } from '@/utils/dictMixin';
import Chart1 from '@/charts/preSale/chart1';
import { authority } from '@/utils/authMixin';
import { integration,integrations,GetPercent,computedAll,getTextByJs } from '@/utils/index';
import { ObjectAssign } from "@/components/DataMerge";
import moment from 'moment';
export default {
  name: 'clueFunnelAnalysisOEM',
  mixins: [dictionary,authority],
  components: {
    Chart1
  },
  data() {
    return {
      topFilterList: this.createTopFilters(),
      fetchParams: {
        startDate:moment().format("YYYY-MM-DD"),
        endDate:moment().format("YYYY-MM-DD")
      },
      quarterTime: [],
      visible: false,
      dialogTitle: '',
      handleType: '',
      formData: {},
      conf:{ add: '新增', edit: '编辑', show: '显示' },
      loading:false,
      dataSource: [],
      columns: this.createTableColumns(),
      radio1: 'clueIdLevelOne',
      radioList: [{ value: 'clueIdLevelOne', text: '一级来源' }, { value: 'clueIdLevelTwo', text: '二级来源' }, { value: 'clueIdLevelThree', text: '三级来源' }, { value: 'clueIdLevelFour', text: '四级来源' }],
    };
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'SELECT',
          label: '日期维度',
          fieldName: 'dateType',
          placeholder: '请选择',
          initialValue: 'day',
          itemList: [{ value: 'day', text: '日' },{ value: 'week', text: '周' },{ value: 'month', text: '月' },
          { value: 'quarter', text: '季' },{ value: 'year', text: '年' },{ value: 'date', text: '期间' }],
          change:val=>{
            this.changeTemplateType(val);
          }
        },
        {
          type: 'DATE',
          label: '日期',
          fieldName: 'datetime',
          placeholder: '',
          dateType: 'exactdate',
          initialValue: moment().format("YYYY-MM-DD"),
          change:(val,fieldName)=>{
            // console.log(val,fieldName)
            this.quarterTime = val;
          }
        },
        {
          type: 'SELECT',
          label: '区域',
          fieldName: 'area',
          placeholder: '请选择...',
          itemList: [],
          change:val=>{
            // console.log(val)
            this.getSaleInfoMaintain(val)
          }
        },
        {
          type: 'INPUT_CASCADER',
          label: '省市',
          fieldName: 'ProvincesCities',
          placeholder: '请选择...',
          options: { titles: ['省', '市'] },
          itemList: [],
          change:val=>{
            // console.log(val)
            this.getSaleInfoMaintain(null,val)
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '经销商',
          fieldName: 'dealerId',
          placeholder: '请选择...',
          itemList: []
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '来源',
          dataIndex: 'clueNameLevelOne',
        },
        {
          title: '线索',
          align: 'center',
          children: [
            {
              title: '总线索',
              dataIndex: 'allTotal',
            },
            {
              title: '新增线索',
              dataIndex: 'total',
            },
            {
              title: '唯一线索',
              dataIndex: 'uniqueTotal',
            },
            {
              title: '有效线索',
              dataIndex: 'validTotal',
            },
            {
              title: '线索有效率',
              dataIndex: 'validTotalRate',
            },
            {
              title: '重复线索',
              dataIndex: 'duplicateTotal',
            },
            {
              title: '线索重复率',
              dataIndex: 'duplicateTotalRate',
            },
          ]
        },
        {
          title: '邀约',
          align: 'center',
          children: [
            {
              title: '邀约量',
              dataIndex: 'inviteTotal',
            },
            {
              title: '邀约率',
              dataIndex: 'inviteTotalRate',
            },
            {
              title: '邀约到店量',
              dataIndex: 'arrivedTotal',
            },
            {
              title: '邀约到店率',
              dataIndex: 'arrivedTotalRate',
            },
          ]
        },
        {
          title: '试驾',
          align: 'center',
          children: [
            {
              title: '试乘试驾量',
              dataIndex: 'testDriveTotal',
            },
            {
              title: '试乘试驾率',
              dataIndex: 'testDriveTotalRate',
            },
          ]
        },
        {
          title: '订单',
          align: 'center',
          children: [
            {
              title: '订单量',
              dataIndex: 'orderCount',
            },
            {
              title: '订单率',
              dataIndex: 'orderCountRate',
            },
          ]
        },
        {
          title: '成交',
          align: 'center',
          children: [
            {
              title: '成交量',
              dataIndex: 'completeCount',
            },
            {
              title: '成交率',
              dataIndex: 'completeCountRate',
            },
            {
              title: '订单成交转化率',
              dataIndex: 'orderConversionRate',
            },
          ]
        },
        {
          title: '战败',
          align: 'center',
          children: [
            {
              title: '战败量',
              dataIndex: 'failTotal',
            },
            {
              title: '战败率',
              dataIndex: 'failTotalRate',
            },
          ]
        },
      ];
    },

    async queryClueSourceReport() {
      this.loading = true;
      const res = await queryClueSourceReport(this.fetchParams);
      if (res.resultCode === 200) {
        this.qryClueFunnelTables(res.data.clueSourceDetail)
      }
    },
    async qryClueFunnelTables(clueList) {
      const res = await qryClueFunnelTables(this.fetchParams);
      if (res.resultCode === 200) {
        let list = integrations([clueList,res.data],this.radio1,['allTotal','total','uniqueTotal','validTotal','duplicateTotal','inviteTotal','arrivedTotal','testDriveTotal','orderCount','completeCount','failTotal'])
        // console.log(list)
        switch (this.radio1) {
          case 'clueIdLevelOne':
            this.columns[0].dataIndex = 'clueNameLevelOne'
            break;
          case 'clueIdLevelTwo':
            this.columns[0].dataIndex = 'clueNameLevelTwo'
            break;
          case 'clueIdLevelThree':
            this.columns[0].dataIndex = 'clueNameLevelThree'
            break;
          case 'clueIdLevelFour':
            this.columns[0].dataIndex = 'clueNameLevelFour'
            break;
          default:
            break;
        }
        if (list.length > 0) {
          let all = computedAll(this.columns,list)
          all['clueNameLevelOne'] = '全部'
          all['clueNameLevelTwo'] = '全部'
          all['clueNameLevelThree'] = '全部'
          all['clueNameLevelFour'] = '全部'
          list.unshift(all)
          list.forEach(x=>{
            x['validTotalRate'] = GetPercent(x.validTotal,x.total)
            x['duplicateTotalRate'] = GetPercent(x.duplicateTotal,x.total)
            x['inviteTotalRate'] = GetPercent(x.inviteTotal,x.validTotal)
            x['arrivedTotalRate'] = GetPercent(x.arrivedTotal,x.inviteTotal)
            x['testDriveTotalRate'] = GetPercent(x.testDriveTotal,x.validTotal)
            x['orderCountRate'] = GetPercent(x.orderCount,x.validTotal)
            x['completeCountRate'] = GetPercent(x.completeCount,x.validTotal)
            x['orderConversionRate'] = GetPercent(x.completeCount,x.orderCount)
            x['failTotalRate'] = GetPercent(x.failTotal,x.validTotal)
          })
        }
        // console.log(list)
        this.loading = false;
        this.dataSource = list;
      }
    },
    async getCityList() {
      let self = this;
      //  console.log(this.provinceId,this.cityId,"this.formList3[89]")
      await getlistAllData().then(res=>{
        // console.log('城市', res)
        let province=[],listAllData=[];
        listAllData=res.data
        listAllData.forEach(x=>{
          // 筛选省
          if(x.parentRegionId == null){
            province.push({text:x.regionName,value:`${x.regionId}`})
          }
        })
        province.forEach(y=>{
          let initCity=[]
          listAllData.forEach(x=>{
            // 市
            if(x.parentRegionId == y.value){
              initCity.push({text:x.regionName,value:`${x.regionId}`})
            }
          })
          y.children = initCity
        })
        // this.listAllData = province;
        this.topFilterList.find(item=>item.fieldName==='ProvincesCities').itemList = province;
        // console.log("省市",province)
      })
    },
    async getMerge() {
      const res = await getMerge();
      if (res.resultCode === 200) {
        // console.log(res)
        this.getOrgByOrgType({orgType:res.data.isDisArea === 10041001?15061006:15061007})//15061006:大区 15061007:小区
      }
    },
    async getOrgByOrgType(data) {
      const res = await getOrgByOrgType(data);
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='area').itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getSaleInfoMaintain(area,Cities) {
      let orgId = area === '' ? area:(area || this.topFilterList.find(item=>item.fieldName==='area').initialValue)
      let ProvincesCities = Cities === '' ? Cities:(Cities || this.topFilterList.find(item=>item.fieldName==='ProvincesCities').initialValue || '');
      // debugger
      let data = {
        pageSize: 999,
        orgId: orgId || undefined,
        provinceId: ProvincesCities.split(",")[0] || undefined,
        cityId: ProvincesCities.split(",")[1] || undefined
      }
      const res = await getSaleInfoMaintain(data);
      if (res.resultCode === 200) {
        this.topFilterList.find(item=>item.fieldName==='dealerId').itemList = res.data.map(x => ({ value: x.orgId, text: x.dealerName }));
        this.topFilterList.find(item=>item.fieldName==='dealerId').initialValue = ''
      }
    },
    changeHandle(val) {
      if (val.datetime) {
        switch (val.dateType) {
          case 'day':
            val.startDate = val.datetime
            val.endDate = val.datetime
            break;
          case 'week':
            var weekOfday = moment(val.datetime,'YYYY-MM-DD').format('E');//计算指定日期是这周第几天
            var last_monday = moment(val.datetime).subtract(weekOfday-1, 'days').format('YYYY-MM-DD');//周一日期
            var last_sunday = moment(val.datetime).add(7-weekOfday, 'days').format('YYYY-MM-DD');//周日日期
            // console.log(last_monday,last_sunday)
            val.startDate = last_monday
            val.endDate = last_sunday
            break;
          case 'month':
            var start_monthday = moment(val.datetime).startOf('month').format('YYYY-MM-DD');//月初日期
            var last_monthday = moment(val.datetime).endOf('month').format('YYYY-MM-DD');//月末日期
            // console.log(start_monthday,last_monthday)
            val.startDate = start_monthday
            val.endDate = last_monthday
            break;
          case 'quarter':
            val.startDate = this.quarterTime[0].split(" ")[0]
            val.endDate = this.quarterTime[1].split(" ")[0]
            // console.log(val.startDate,val.endDate)
            break;
          case 'year':
            var start_yearday = moment(val.datetime).startOf('year').format('YYYY-MM-DD');//年初日期
            var last_yearday = moment(val.datetime).endOf('year').format('YYYY-MM-DD');//年末日期
            // console.log(start_yearday,last_yearday)
            val.startDate = start_yearday
            val.endDate = last_yearday
            break;
          case 'date':
            val.startDate = val.datetime[0] ? val.datetime[0]:undefined;
            val.endDate = val.datetime[1] ? val.datetime[1]:undefined;
            break;
          default:
            break;
        }
      }
      if (val.dealerId.length === 0 && (val.area || val.ProvincesCities)) {
        let list = this.topFilterList.find(item=>item.fieldName==='dealerId').itemList;
        val.orgId = getTextByJs(list,'value')
      }else if (val.dealerId.length > 0) {
        val.orgId = getTextByJs(val.dealerId)
      }else{
        val.orgId = val.dealerId
      }
      this.fetchParams = Object.assign({}, val);
      this.queryClueSourceReport()
    },
    changeClue(val){
      this.queryClueSourceReport()
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    // 修改日期组件
    changeTemplateType(val){
      switch (val) {
        case 'day':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'exactdate';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'week':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'week';
          this.topFilterList.find(item=>item.fieldName==='datetime').firstDayOfWeek = 1;
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'month':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'month';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'quarter':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'quarter';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'year':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'year';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'date':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'RANGE_DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'exactdaterange';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        default:
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdate';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
      }
    },

  },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getMerge()
    this.getSaleInfoMaintain()
    this.getCityList()
    this.queryClueSourceReport()
    // this.getConsultant().then((result) => {
    //   this.topFilterList.find(item=>item.fieldName==='consultant').itemList = result;
    // })
  }
};
</script>

<style lang="less" scoped>
</style>
